package com.yzq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yzq.enums.ErrorCode;
import com.yzq.model.entity.Classify;
import com.yzq.service.ClassifyService;
import com.yzq.mapper.ClassifyMapper;
import com.yzq.utils.ThrowUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
* @author yezhi
* @description 针对表【classify】的数据库操作Service实现
* @createDate 2025-07-09 14:51:23
*/
@Service
public class ClassifyServiceImpl extends ServiceImpl<ClassifyMapper, Classify>
    implements ClassifyService{

    @Override
    public boolean addClassify(Classify classify) {
        ThrowUtils.throwIf(classify == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(classify.getName().isEmpty(), ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(classify.getName().length() > 20, ErrorCode.BAD_REQUEST);
        classify.setCreateTime(new Date());
        classify.setUpdateTime(new Date());
        return save(classify);
    }

    @Override
    public boolean deleteClassify(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.BAD_REQUEST);
        return removeById(id);
    }

    @Override
    public boolean updateClassify(Classify classify) {
        ThrowUtils.throwIf(classify == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(classify.getId() == null, ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(classify.getName().isEmpty(), ErrorCode.BAD_REQUEST);
        ThrowUtils.throwIf(classify.getName().length() > 20, ErrorCode.BAD_REQUEST);

        // 判断分类是否存在
        Classify oldClassify = getById(classify.getId());
        ThrowUtils.throwIf(oldClassify == null, ErrorCode.NOT_FOUND);
        ThrowUtils.throwIf(!oldClassify.getName().equals(classify.getName()), ErrorCode.CONFLICT, "分类重复更改");

        // 查询分类名称是否重复
        QueryWrapper<Classify> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", classify.getName());
        Classify newClassify = getOne(queryWrapper);
        ThrowUtils.throwIf(newClassify != null && !newClassify.getId().equals(classify.getId()), ErrorCode.CONFLICT, "分类重复");
        classify.setUpdateTime(new Date());
        return updateById(classify);
    }

    /**
     * 获取所有分类
     * @return List<Classify>
     */
    @Override
    public List<Classify> getAllClassifies() {
        return list();
    }

    /**
     *  获取分类
     * @param id 分类ID
     * @return Classify
     */
    @Override
    public Classify getClassifyById(Long id) {
        ThrowUtils.throwIf(id == null, ErrorCode.BAD_REQUEST);
        return getById(id);
    }
}




